<template>
    <div class="assessment-result-page">
        <!-- 导航栏 -->
        <van-nav-bar title="评估结果" left-text="返回" left-arrow @click-left="handleBack">
            <template #right>
                <van-icon name="share-o" @click="shareResult" />
            </template>
        </van-nav-bar>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-section">
            <van-loading size="24px" vertical>分析中...</van-loading>
        </div>

        <!-- 结果内容 -->
        <div v-else-if="result" class="result-content">
            <!-- 总体评分 -->
            <div class="overall-score-section">
                <div class="score-container">
                    <div class="score-circle">
                        <div class="score-number">{{ result.overall_score }}</div>
                        <div class="score-label">综合评分</div>
                    </div>
                    <div class="score-description">
                        <h3>{{ getScoreLevel(result.overall_score) }}</h3>
                        <p>{{ getScoreDescription(result.overall_score) }}</p>
                    </div>
                </div>
            </div>

            <!-- 能力雷达图 -->
            <div class="radar-section">
                <div class="section-header">
                    <h3>能力分析</h3>
                    <van-button size="small" type="primary" plain @click="viewDetailedAbilities">
                        查看详情
                    </van-button>
                </div>
                <div class="radar-container">
                    <RadarChart :data="radarData" />
                </div>
            </div>

            <!-- 能力详情 -->
            <div class="abilities-section">
                <h3>各项能力评分</h3>
                <div class="ability-items">
                    <div v-for="ability in result.abilities" :key="ability.ability_type" class="ability-item">
                        <div class="ability-info">
                            <div class="ability-header">
                                <span class="ability-name">{{ ability.ability_name }}</span>
                                <span class="ability-score">{{ ability.score }}/10</span>
                            </div>
                            <div class="ability-progress">
                                <van-progress :percentage="(ability.score / 10) * 100" stroke-width="6"
                                    :color="getProgressColor(ability.score)" />
                            </div>
                            <div class="ability-description">
                                {{ ability.description }}
                            </div>
                        </div>
                        <div class="ability-level">
                            <span :class="getLevelClass(ability.score)">
                                {{ getAbilityLevel(ability.score) }}
                            </span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 改进建议 -->
            <div class="suggestions-section">
                <h3>个性化建议</h3>
                <div class="suggestions-list">
                    <div v-for="(suggestion, index) in result.suggestions" :key="index" class="suggestion-item">
                        <div class="suggestion-icon">
                            <van-icon name="bulb-o" />
                        </div>
                        <div class="suggestion-content">
                            <h4>{{ suggestion.title }}</h4>
                            <p>{{ suggestion.description }}</p>
                            <div v-if="suggestion.actions" class="suggestion-actions">
                                <van-tag v-for="action in suggestion.actions" :key="action" size="small" type="primary"
                                    plain>
                                    {{ action }}
                                </van-tag>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 推荐训练 -->
            <div class="training-section">
                <h3>推荐训练</h3>
                <div class="training-list">
                    <div v-for="training in recommendedTrainings" :key="training.id" class="training-item"
                        @click="startTraining(training)">
                        <div class="training-info">
                            <h4>{{ training.title }}</h4>
                            <p>{{ training.description }}</p>
                            <div class="training-meta">
                                <van-tag size="small">{{ training.difficulty }}</van-tag>
                                <span class="training-duration">{{ training.duration }}</span>
                            </div>
                        </div>
                        <van-icon name="arrow" />
                    </div>
                </div>
            </div>
        </div>

        <!-- 操作按钮 -->
        <div class="result-actions">
            <van-button type="primary" size="large" block @click="startImprovement">
                开始能力提升
            </van-button>
            <van-button type="default" size="large" block @click="retakeAssessment">
                重新评估
            </van-button>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast } from 'vant'
import { assessmentApi, trainingApi, type AssessmentResult, type TrainingScenario } from '@/api'
import { useUserStore } from '@/stores/user'
import RadarChart from '@/components/RadarChart.vue'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 响应式数据
const loading = ref(true)
const result = ref<AssessmentResult | null>(null)
const recommendedTrainings = ref<TrainingScenario[]>([])

// 计算属性
const radarData = computed(() => {
    if (!result.value) return null

    return {
        labels: result.value.abilities.map((ability: any) => ability.ability_name),
        datasets: [{
            label: '当前能力',
            data: result.value.abilities.map((ability: any) => ability.score),
            backgroundColor: 'rgba(25, 137, 250, 0.2)',
            borderColor: '#1989fa',
            borderWidth: 2,
            pointBackgroundColor: '#1989fa',
            pointBorderColor: '#fff',
            pointBorderWidth: 2
        }]
    }
})

// 方法
const loadResult = async () => {
    try {
        loading.value = true
        const userId = parseInt(route.params.assessmentId as string)

        // 获取用户能力数据
        const abilitiesResponse = await userApi.getUserAbilities(userId)
        const abilityData = abilitiesResponse.data

        // 转换数据格式以匹配前端期望的结构
        const currentAbilities = abilityData.current_abilities
        const overallScore = currentAbilities.total_score

        result.value = {
            id: userId,
            overall_score: overallScore,
            abilities: [
                {
                    ability_type: 'breaking_ice',
                    ability_name: 'Breaking Ice',
                    score: currentAbilities.breaking_ice,
                    description: `Current breaking ice level is ${currentAbilities.breaking_ice}/100`
                },
                {
                    ability_type: 'empathy',
                    ability_name: 'Empathy',
                    score: currentAbilities.empathy,
                    description: `Current empathy level is ${currentAbilities.empathy}/100`
                },
                {
                    ability_type: 'conversation_flow',
                    ability_name: 'Conversation Flow',
                    score: currentAbilities.conversation_flow,
                    description: `Current conversation flow level is ${currentAbilities.conversation_flow}/100`
                }
            ],
            suggestions: abilityData.improvement_suggestions.map((suggestion: any) => ({
                title: suggestion.title,
                description: suggestion.suggestion,
                actions: ['Practice More', 'Join Training']
            })),
            created_at: new Date().toISOString()
        }

        // 获取推荐训练（暂时使用模拟数据）
        recommendedTrainings.value = []
    } catch (error) {
        console.error('加载评估结果失败:', error)
        showToast('加载结果失败，请重试')
    } finally {
        loading.value = false
    }
}

const getScoreLevel = (score: number) => {
    if (score >= 8.5) return '优秀'
    if (score >= 7.0) return '良好'
    if (score >= 5.5) return '中等'
    if (score >= 4.0) return '待提升'
    return '需要加强'
}

const getScoreDescription = (score: number) => {
    if (score >= 8.5) return '您的社交能力表现优异，在各个方面都有很好的表现。'
    if (score >= 7.0) return '您的社交能力整体良好，在某些方面还有提升空间。'
    if (score >= 5.5) return '您的社交能力处于中等水平，通过训练可以获得显著提升。'
    if (score >= 4.0) return '您的社交能力有待提升，建议重点关注薄弱环节。'
    return '您的社交能力需要系统性的训练和提升。'
}

const getAbilityLevel = (score: number) => {
    if (score >= 8) return '优秀'
    if (score >= 6) return '良好'
    if (score >= 4) return '中等'
    return '待提升'
}

const getLevelClass = (score: number) => {
    if (score >= 8) return 'level-excellent'
    if (score >= 6) return 'level-good'
    if (score >= 4) return 'level-average'
    return 'level-poor'
}

const getProgressColor = (score: number) => {
    if (score >= 8) return '#07c160'
    if (score >= 6) return '#ffd21e'
    if (score >= 4) return '#ff976a'
    return '#ee0a24'
}

const viewDetailedAbilities = () => {
    router.push('/abilities/radar')
}

const startTraining = (training: TrainingScenario) => {
    router.push({
        name: 'TrainingSession',
        params: { scenarioId: training.id }
    })
}

const startImprovement = () => {
    router.push('/training')
}

const retakeAssessment = () => {
    router.push('/assessment')
}

const shareResult = () => {
    showToast('分享功能')
}

const handleBack = () => {
    router.push('/home')
}

// 生命周期
onMounted(() => {
    loadResult()
})
</script>

<style lang="scss" scoped>
.assessment-result-page {
    min-height: 100vh;
    background: #f7f8fa;
    padding-bottom: 120px;

    .loading-section {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 300px;
    }

    .result-content {
        padding-bottom: 20px;
    }

    .overall-score-section {
        background: linear-gradient(135deg, #1989fa 0%, #1c7cd6 100%);
        color: white;
        padding: 30px 20px;
        margin-bottom: 12px;

        .score-container {
            display: flex;
            align-items: center;
            gap: 24px;

            .score-circle {
                width: 100px;
                height: 100px;
                border: 3px solid rgba(255, 255, 255, 0.3);
                border-radius: 50%;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                flex-shrink: 0;

                .score-number {
                    font-size: 32px;
                    font-weight: bold;
                    line-height: 1;
                }

                .score-label {
                    font-size: 12px;
                    opacity: 0.8;
                    margin-top: 4px;
                }
            }

            .score-description {
                flex: 1;

                h3 {
                    font-size: 24px;
                    margin: 0 0 8px 0;
                    font-weight: 600;
                }

                p {
                    font-size: 14px;
                    opacity: 0.9;
                    line-height: 1.5;
                    margin: 0;
                }
            }
        }
    }

    .radar-section {
        background: white;
        padding: 20px;
        margin-bottom: 12px;

        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;

            h3 {
                font-size: 18px;
                color: #323233;
                margin: 0;
            }
        }

        .radar-container {
            height: 300px;
        }
    }

    .abilities-section {
        background: white;
        padding: 20px;
        margin-bottom: 12px;

        h3 {
            font-size: 18px;
            color: #323233;
            margin: 0 0 20px 0;
        }

        .ability-items {
            .ability-item {
                display: flex;
                align-items: center;
                padding: 16px 0;
                border-bottom: 1px solid #f5f5f5;

                &:last-child {
                    border-bottom: none;
                }

                .ability-info {
                    flex: 1;

                    .ability-header {
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                        margin-bottom: 8px;

                        .ability-name {
                            font-size: 16px;
                            color: #323233;
                            font-weight: 500;
                        }

                        .ability-score {
                            font-size: 16px;
                            color: #1989fa;
                            font-weight: bold;
                        }
                    }

                    .ability-progress {
                        margin-bottom: 8px;
                    }

                    .ability-description {
                        font-size: 12px;
                        color: #646566;
                        line-height: 1.4;
                    }
                }

                .ability-level {
                    margin-left: 16px;

                    span {
                        padding: 4px 8px;
                        border-radius: 4px;
                        font-size: 12px;
                        font-weight: 500;

                        &.level-excellent {
                            background: #f0f9ff;
                            color: #07c160;
                        }

                        &.level-good {
                            background: #fffbf0;
                            color: #ffd21e;
                        }

                        &.level-average {
                            background: #fff7f0;
                            color: #ff976a;
                        }

                        &.level-poor {
                            background: #fff1f0;
                            color: #ee0a24;
                        }
                    }
                }
            }
        }
    }

    .suggestions-section {
        background: white;
        padding: 20px;
        margin-bottom: 12px;

        h3 {
            font-size: 18px;
            color: #323233;
            margin: 0 0 20px 0;
        }

        .suggestions-list {
            .suggestion-item {
                display: flex;
                gap: 12px;
                padding: 16px 0;
                border-bottom: 1px solid #f5f5f5;

                &:last-child {
                    border-bottom: none;
                }

                .suggestion-icon {
                    width: 32px;
                    height: 32px;
                    background: #fff7e6;
                    border-radius: 50%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    flex-shrink: 0;

                    .van-icon {
                        color: #ffd21e;
                    }
                }

                .suggestion-content {
                    flex: 1;

                    h4 {
                        font-size: 16px;
                        color: #323233;
                        margin: 0 0 8px 0;
                        font-weight: 500;
                    }

                    p {
                        font-size: 14px;
                        color: #646566;
                        line-height: 1.5;
                        margin: 0 0 12px 0;
                    }

                    .suggestion-actions {
                        display: flex;
                        gap: 8px;
                        flex-wrap: wrap;
                    }
                }
            }
        }
    }

    .training-section {
        background: white;
        padding: 20px;
        margin-bottom: 12px;

        h3 {
            font-size: 18px;
            color: #323233;
            margin: 0 0 20px 0;
        }

        .training-list {
            .training-item {
                display: flex;
                align-items: center;
                padding: 16px 0;
                border-bottom: 1px solid #f5f5f5;
                cursor: pointer;

                &:last-child {
                    border-bottom: none;
                }

                &:active {
                    background: #f7f8fa;
                }

                .training-info {
                    flex: 1;

                    h4 {
                        font-size: 16px;
                        color: #323233;
                        margin: 0 0 8px 0;
                        font-weight: 500;
                    }

                    p {
                        font-size: 14px;
                        color: #646566;
                        line-height: 1.5;
                        margin: 0 0 8px 0;
                    }

                    .training-meta {
                        display: flex;
                        align-items: center;
                        gap: 12px;

                        .training-duration {
                            font-size: 12px;
                            color: #969799;
                        }
                    }
                }
            }
        }
    }

    .result-actions {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        background: white;
        padding: 16px 20px;
        border-top: 1px solid #ebedf0;
        display: flex;
        gap: 12px;

        .van-button {
            flex: 1;
        }
    }
}
</style>